package com.fruit.service.order.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.fruit.constants.AfterSalesServiceConstant;
import com.fruit.constants.OrderConstant;
import com.fruit.constants.PayConstant;
import com.fruit.mapper.order.OrderMapper;
import com.fruit.mapper.pay.PayMapper;
import com.fruit.mapper.refund.AfterSalesServiceMapper;
import com.fruit.pojo.common.Page;
import com.fruit.pojo.order.Invoice;
import com.fruit.pojo.order.Order;
import com.fruit.pojo.order.OrderGood;
import com.fruit.pojo.order.OrderGoods;
import com.fruit.pojo.order.OrderReason;
import com.fruit.pojo.order.OrderView;
import com.fruit.pojo.refund.AfterSalesService;
import com.fruit.pojo.refund.AfterSalesServiceGoods;
import com.fruit.pojo.refund.OrderRufund;
import com.fruit.pojo.refund.Question;
import com.fruit.pojo.user.ComAccount;
import com.fruit.pojo.user.Address;
import com.fruit.service.order.OrderManager;
import com.fruit.util.CustomUtil;
import com.fruit.util.DateUtil;
import com.fruit.util.ResultInfo;
import com.fruit.util.ResultUtil;


/** 订单
 * 修改时间：2016.07.15
 */
@Service("orderService")
public class OrderService implements OrderManager{
	
	@Autowired
	private PayMapper payMapper;
	
	@Autowired
	private OrderMapper orderMapper;
	
	@Autowired
	private AfterSalesServiceMapper afterSalesServiceMapper;
	
	@Override
	public List<Map<String, Object>> getOrderList(Map<String, Object> parame) {
		return orderMapper.getOrderList(parame);
	}

	@Override
	public Order getOrder(String oid) {
		return orderMapper.getOrder(oid);
	}

	@Override
	public void updateOrderState(Order order) {
		orderMapper.updateOrderState(order);
	}

	@Override
	public Map<String, Object> getOrderDetails(Page page) {
		Map<String, Object> resMa = new HashMap<String, Object>();
		List<Map<String, Object>> resMaps=orderMapper.getOrderDetails(page);
		if(resMaps==null || resMaps.size()<0){
			resMa.put("result", ResultUtil.initResult(ResultInfo.ERROR, "params_error", "未找到订单!"));
			return resMa;
		}
		Address shop=orderMapper.getOrderReceiver((String)page.getParams().get("oid"));
		if(shop == null){
			resMa.put("result", ResultUtil.initResult(ResultInfo.ERROR, "address_error", "未找到订单收货地址!"));
			return resMa;
		}
		ComAccount ca=orderMapper.getComAss();
		if(ca == null){
			resMa.put("result", ResultUtil.initResult(ResultInfo.ERROR, "account_error", "未找到订单收款账户!"));
			return resMa;
		}
		Invoice i=orderMapper.getInvoice((String)page.getParams().get("oid"));
		if(i != null){
			if("00".equals(i.getType())){
				i.setType("个人");
			}else{
				i.setType("公司");
			} 
		}
	
		Map<String, Order> dateilMap = new HashMap<String, Order>();
		for (Map<String, Object> resMap : resMaps) {
			if("00".equals(resMap.get("state"))){
				resMap.put("stateName", "未付款");
			}else if("02".equals(resMap.get("state"))){
				resMap.put("stateName", "待发货");
			}else if("03".equals(resMap.get("state"))){
				resMap.put("stateName", "待收货");
			}else if("04".equals(resMap.get("state"))){
				resMap.put("stateName", "已完成");
			}else if("05".equals(resMap.get("state"))){
				resMap.put("stateName", "已取消");
			}else if("06".equals(resMap.get("state"))){
				resMap.put("stateName", "已退款");
			}
			if(PayConstant.PAY_TYPE_ALL.equals(resMap.get("payType"))){
				resMap.put("payType", "全款");
			}
			OrderGood g =new OrderGood();
			g.setGoodsId((int)resMap.get("goodsId"));
			g.setGoodsThumb((String)resMap.get("goodsThumb"));
			g.setTitle((String)resMap.get("title"));
			g.setNumber((int)resMap.get("number"));
			g.setTradePrice((BigDecimal)resMap.get("tradePrice"));
			g.setRefundState((String)resMap.get("refundState1"));
			g.setUnit((String) resMap.get("unit"));
			g.setUnitDesc((String) resMap.get("unitDesc"));
			long id=(long)resMap.get("orderId");
			if (!dateilMap.containsKey(id + "s")) {
				Order o = new Order();
				o.getOrderGood().add(g);
				o.setPayMode((String)resMap.get("payMode"));
				o.setPayType((String)resMap.get("payType"));
				o.setId((int)id);
				String codePre = (String) resMap.get("codePre");
				String codeSuf = (String) resMap.get("codeSuf");
				o.setCodePre(codePre);
				o.setCodeSuf(codeSuf);
				o.setOrderCode(codePre+id+codeSuf);
				o.setSupplierName((String) resMap.get("supplier"));
				o.setUserId((int)resMap.get("userId"));
				o.setOrderTyp((String)resMap.get("type"));
				o.setState((String)resMap.get("state"));
				o.setStateName((String)resMap.get("stateName"));
				o.setTotalPrice((BigDecimal)resMap.get("totalPrice"));
				o.setRealPrice((BigDecimal)resMap.get("realPrice"));
				o.setCreateTime((String)resMap.get("createTime"));
				o.setClosingTime((String)resMap.get("closingTime"));
				o.setDeliveryTime((String)resMap.get("deliveryTime"));
				o.setExpectDeliveryTime((String)resMap.get("expectDeliveryTime"));
				o.setRemittanceCode((String)resMap.get("remittanceCode"));
				o.setRefundState((String)resMap.get("refundState"));
				o.setAccount(ca);
				o.setAddress(shop);
				o.setInvoice(i);
				if(i != null){
					o.setInvoiceType("01");
				}else{
					o.setInvoiceType("00");
				}
				dateilMap.put(Long.toString(id)+"s", o);
			}else{
				Order o = dateilMap.get(Long.toString(id)+"s");
				o.getOrderGood().add(g);
			}
		}
		Collection<Order> valueCollection = dateilMap.values();
		List<Order> resOrderList = new ArrayList<Order>(valueCollection);
		resMa.put("dateilMap", resOrderList);
		resMa.put("result", ResultUtil.initResult(ResultInfo.SUCCESS, "SUCCESS", "查询成功!"));
		return resMa;
	}

	@Override
	public Map<String, Object> getEarnest(String oid) {
		return orderMapper.getEarnest(oid);
	}

	@Override
	public OrderView getOrderDe(Page page) {
		return orderMapper.getOrderDe(page);
	}

	@Override
	public void updateOrderShow(Page page) {
		orderMapper.updateOrderShow(page);
	}

	@Override
	public int saveRefund(OrderRufund or,OrderView ov) {
		or.setCodePre(DateUtil.getYear());
		or.setCodeSuf(CustomUtil.buildRandom(7) + "");
		or.setType(OrderConstant.REFUND);
		or.setCreateTime(DateUtil.getTime());
		int num = orderMapper.saveRefund(or);
		if(num >0){
			Order o =new Order();
			o.setIsRefund("01");
			o.setRefundId(or.getId());
			o.setVersion(ov.getVersion());
			o.setId(or.getOrderId());
			orderMapper.updateOrderRe(o);
		}else{
			return 0;
		}
		return 1;
	}

	@Override
	public List<OrderGood> getOrderGoods(Page page) {
		return orderMapper.getOrderGoods(page);
	}

	@Override
	public List<OrderReason> getOrderReason() {
		return orderMapper.getOrderReason();
	}

	@Override
	public Map<String, Object> saveSalesService(Order order, String id) {
		Map<String, Object> resMap = new HashMap<String, Object>();
		 AfterSalesService as = new AfterSalesService();
		 as.setCodePre(DateUtil.getYear());
		 as.setCodeSuf(CustomUtil.codeSuf(3,order.getUserId()));
		 as.setOrderCode(order.getCodePre()+order.getId()+order.getCodeSuf());
		 as.setOrderId(order.getId());
		 as.setUserId(order.getUserId());
		 as.setIsAuto(AfterSalesServiceConstant.NO_AUTO);
		 as.setType(AfterSalesServiceConstant.TYPE_CANCEL);
		 as.setState(AfterSalesServiceConstant.STATE_FINISH);
		 as.setCreateTime(DateUtil.getTime());
		 int num = afterSalesServiceMapper.saveSalesService(as);
		 if(num <=0){
			resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "again_start", "网络异常"));
			return resMap;
		 }
		 OrderReason or=orderMapper.getReason(id);
		 if(or == null){
			 resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "again_start", "请选择取消原因"));
			 return resMap; 
		 }
		 Question tion = new Question();
		 tion.setAfterSalesServiceId(as.getId());
		 tion.setContent(or.getReason());
		 tion.setUserId(String.valueOf(order.getUserId()));
		 tion.setIsUser(AfterSalesServiceConstant.AUTO);
		 tion.setCreateTime(DateUtil.getTime());
		 num=orderMapper.saveQuestion(tion);
		 if(num <=0){
			resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "again_start", "网络异常"));
			return resMap;
		 }
		 order.setState("05");
		 orderMapper.updateOrderState(order);
		 List<OrderGoods> ogList = orderMapper.getOrderGoodsList(order);
		 if(ogList != null){
			 for(OrderGoods og : ogList){
				 payMapper.updateAddGoodsStockNum(og);
			 }
		 }
		 
		 resMap.put("result", ResultUtil.initResult(ResultInfo.SUCCESS, "SUCCESS", "取消成功"));
		return resMap;
	}

	@Override
	public Map<String, Object> getRefundOrderList(Map<String, Object> parame) {
		Map<String, Object> resMap = new HashMap<String, Object>();
		 Map<String, Object> orderMap = new TreeMap<String, Object>(Collections.reverseOrder());
		List<Map<String, Object>> order = orderMapper.getRefundOrderList(parame);
		if(order == null || order.size()==0){
			resMap.put("result", ResultUtil.initResult(ResultInfo.SUCCESS, "order-null", "未找到订单"));
			return resMap;
		}
		
		for (Map<String, Object> map : order) {
			long id=(long)map.get("id");
			String codePre=(String)map.get("codePre");
			String codeSuf=(String)map.get("codeSuf");
			if("00".equals(map.get("state"))){
				map.put("stateName", "审核中");
				map.put("describe", "您的服务单号为"+codePre+id+codeSuf+"平台正在审核中");
			}else if("01".equals(map.get("state"))){
				map.put("stateName", "正在处理");
				map.put("describe", "您的服务单号为"+codePre+id+codeSuf+"平台正在处理");
			}else if("02".equals(map.get("state"))){
				map.put("stateName", "已完成");
				map.put("describe", "您的服务单号为"+codePre+id+codeSuf+"平台已退款,请查收");
			}else if("03".equals(map.get("state"))){
				map.put("stateName", "拒绝");
			}
			AfterSalesServiceGoods goods =new AfterSalesServiceGoods();
			goods.setTitle((String)map.get("title"));
			goods.setGoodsId((int)map.get("goodsId"));
			goods.setGoodsThumb((String)map.get("thumb"));
			if (!orderMap.containsKey(id + "s")) {
				AfterSalesService ss= new AfterSalesService();
				ss.setOrderCode((String)map.get("orderCode"));
				ss.setCreateTime((String)map.get("createTime"));
				ss.setState((String)map.get("state"));
				ss.setStateName((String)map.get("stateName"));
				ss.setId(id);
				ss.setCodePre(codePre);
				ss.setCodeSuf(codeSuf);
				ss.setServiceCode(codePre+id+codeSuf);
				ss.setDescribe((String)map.get("describe"));
				ss.getOrderGoods().add(goods);
				orderMap.put(Long.toString(id) + "s", ss);
			}else{
				AfterSalesService ss=(AfterSalesService)orderMap.get(id+"s");
				ss.getOrderGoods().add(goods);
			}
			Collection<Object> valueCollection = orderMap.values();
			List<Object> resOrderList = new ArrayList<Object>(valueCollection);
			resMap.put("refundList", resOrderList);
			resMap.put("result", ResultUtil.initResult(ResultInfo.SUCCESS, "SUCCESS", "查询成功!"));
		}
		return resMap;
	}
	
}
